import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType} from '@ant-design/pro-table';
import type {TableListItem} from './data.d';
import {queryType} from "./data.d";
import {queryContractList, queryUsdtContract} from './service';
import {queryUse, queryUseUpdate} from "@/utils/service";
import {columnsSorter, columnToColumnsState, empty} from "@/utils/function";
import {Button, Card, Upload} from 'antd';
import {UploadOutlined} from '@ant-design/icons';


const ContractList: React.FC = () => {
  /** 新建窗口的弹窗 */
  /*
  * adminId: 2
avgPrice: 0
closePosition: false
cumQty: 0.012
executedQty: 0
id: 9
leverage: 2
orderId: 8389765496076330000
origType: "MARKET"
priceProtect: false
reduceOnly: false
side: "SELL"
status: "NEW"
stopPrice: 0
symbol: "ETHUSDT"
type: "MARKET"
updateTime: 1619589363798
  * */
  const columns: any[] = [
    {
      title: "订单ID",
      dataIndex: 'orderId',
      key: 'orderId',
      fixed: "left",
      width: 100,
      // filters: true,
      // onFilter: true,
      tip: '订单ID是唯一的 key',
    },
    {
      title: "交易对",
      search: false,
      dataIndex: 'symbol',
      key: 'symbol',
      fixed: "left",
      width: 90,
    },
    {
      title: "原始订单数量",
      search: false,
      width: 80,
      dataIndex: 'cumQty',
      key: 'cumQty',
    },
    {
      title: "交易的订单数量",
      search: false,
      width: 80,
      dataIndex: 'executedQty',
      key: 'executedQty',
    },
    {
      title: "均价",
      search: false,
      width: 100,
      dataIndex: 'avgPrice',
      key: 'avgPrice',
    },
    {
      title: "订单状态",
      search: false,
      width: 80,
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: "订单的时效方式",
      search: false,
      width: 100,
      dataIndex: 'timeInForce',
      key: 'timeInForce',
    },
    {
      title: "订单类型",
      search: false,
      width: 80,
      key: 'origType',
      dataIndex: 'origType',
    },
    {
      title: "买卖方向",
      search: false,
      width: 80,
      dataIndex: 'side',
      key: 'side',
    },
  ];
  const actionRef = useRef<ActionType>();
  columnsSorter("ContractList合约下单记录列表", columns);
  const [col, setCol] = useState<any>(columnToColumnsState(columns));
  const uploadProps = {
    name: 'excelFile',
    action: '/hk/admin/billDetails/wallet',
    headers: {
      authorization: 'authorization-text',
      'token':`${localStorage.getItem('token')}`
    },
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        queryUseUpdate(info.file.response);
        //   message.success(`${info.file.name} file uploaded successfully`);
        // } else if (info.file.status === 'error') {
        //   message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  return (
    <PageContainer>
      <Card>
      <ProTable<TableListItem>
        headerTitle={"合约下单记录列表"}
        rowKey="key"
        bordered
        actionRef={actionRef}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        columnsStateMap={col}
        onColumnsStateChange={(e) => {
          if (!empty(e)) {
            localStorage.setItem("ContractList合约下单记录列表", JSON.stringify(e));
            setCol(e);
          }
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={async () => {
              const msg = await queryUsdtContract();
              queryUseUpdate(msg);
            }}
            style={{margin: "15px"}}
          >
            获取流水
          </Button>,
          <Upload {...uploadProps} showUploadList={false}>
            <Button style={{marginRight: "25px"}} icon={<UploadOutlined/>}>上传excel</Button>
          </Upload>,
        ]}
        scroll={{x: 1200, y: 666}}
        request={async (params = {}, sort, filter) => {
          // console.log(sort, filter);
          let payload: queryType = {
            // "adminId": 0,
            // "endTime": 0,
            group: "",
            // "orderId": "",
            // "startTime": 0
            page: params.current,
            pageSize: params.pageSize,
          }
          /*{
	"adminId": 0,
	"endTime": 0,
	"group": "",
	"orderId": "",
	"page": 0,
	"pageSize": 0,
	"startTime": 0
}*/
          if (params.orderId) {
            payload = {...payload, orderId: params.orderId}
          }
          const msg = await queryContractList(
            payload
          );
          let data = queryUse(msg)
          if (data) {
            return {
              data: data.list,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: data.total,
            };
          } else {
            return {
              data: [],
              success: false,
            };
          }
        }}
        columns={columns}
        pagination={{defaultPageSize: 50}}
      />

      </Card>
    </PageContainer>
  );
};

export default ContractList;
